import { BaseChartConfig } from './../basechartconfig.js';
import { TemplateManager } from '/src/util/templatemanager/templatemanager.js';

export class ChartPieConfig extends BaseChartConfig {
    constructor(container, options) {
        super(container, options);
    }

    getConfigData(chart) {
        const keyProperties = ['name'];
        if (!chart) return {};
        const result = chart.getOption()['series'][0]['data'].reduce((acc, item) => {
            const key = item.lastName;
            if (key) {
                const filteredItem = {};
                keyProperties.forEach(prop => {
                    if (item.hasOwnProperty(prop)) {
                        filteredItem[prop] = item[prop];
                    }
                });
                acc[key] = filteredItem;
            }
            return acc;
        }, {});

        result['innerRadius'] = $(`#innerRadius-${this.cid}`).val();
        result['outerRadius'] = $(`#outerRadius-${this.cid}`).val();

        return result;
    }

    async generateConfigForm() {
        await this.generateBaseConfigForm();
        await this.generateSeriesConfigForm();
    }

    async generateSeriesConfigForm() {
        this.$seriesConfigContainer.empty();

        try {
            const html = await TemplateManager.loadTemplate('/src/components/component/chart/config/pie/chart-series-config.html', {
                cid: this.cid
            });
            this.$seriesConfigContainer.append(html);

            $(`#innerRadius-${this.cid}`).val(0);
            $(`#outerRadius-${this.cid}`).val(50);

            this.bindPieConfigEvents();

            this.generateDataItemsConfig();

        } catch (error) {
            console.error('加载饼图配置模板失败', error);
        }
    }

    generateDataItemsConfig() {
        const $container = this.$seriesConfigContainer;

        if (this.data && this.data.seriesPie) {
            this.data.seriesPie.data.forEach((dataItem, index) => {
                const itemHtml = `
                    <div class="mb-2 p-2 border rounded">
                        <label class="form-label small">数据项 ${index + 1}</label>
                        <input id="dataItemName-${this.cid}-${index}" type="text" class="form-control form-control-sm" value="${dataItem.name || ''}" placeholder="请输入名称" />
                    </div>
                `;
                $container.append(itemHtml);
                this.bindDataItemNameEvent(index, dataItem);
            });
        }
    }

    bindDataItemNameEvent(index, dataItem) {
        const $nameInput = $(`#dataItemName-${this.cid}-${index}`);

        $nameInput.on('input', (e) => {
            const name = e.target.value;
            this.updateDataItemConfig(index, { name });
        });
    }

    updateDataItemConfig(index, config) {
        if (!this.data || !this.data.seriesPie) {
            console.warn('饼图数据不存在');
            return;
        }

        // 更新数据项配置
        Object.assign(this.data.seriesPie.data[index], config);
        this.data.legend[index] = config.name;
        // 触发配置变更事件
        this.trigger('configChanged', {
            type: 'dataItem',
            index: index,
            config: config
        });
    }

    bindPieConfigEvents() {
        $(`#innerRadius-${this.cid}`).on('input', e => {
            const innerRadius = e.target.value;
            const outerRadius = $(`#outerRadius-${this.cid}`).val();
            this.updatePieRadius(innerRadius, outerRadius);
        });

        $(`#outerRadius-${this.cid}`).on('input', e => {
            const outerRadius = e.target.value;
            const innerRadius = $(`#innerRadius-${this.cid}`).val();
            this.updatePieRadius(innerRadius, outerRadius);
        });
    }

    updatePieRadius(innerRadius, outerRadius) {
        if (!this.data || !this.data.seriesPie) {
            console.warn('饼图数据不存在');
            return;
        }
        const radius = [`${innerRadius}%`, `${outerRadius}%`];
        this.data.seriesPie.radius = radius;
        this.trigger('configChanged', {
            radius: radius,
            innerRadius: innerRadius,
            outerRadius: outerRadius
        });
    }
}